package com.eralink.unionuhfreader.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eralink.uhfreaderlib.EraLinkUHFReaderCmdCode;
import com.eralink.uhfreaderlib.EraLinkUHFReaderInterface;
import com.eralink.uhfreaderlib.EraLinkUHFReaderReportCallback;
import com.eralink.unionuhfreader.MyApplication;
import com.eralink.unionuhfreader.R;
import com.eralink.unionuhfreader.adapter.ManualCateRecycleViewAdapter;
import com.eralink.unionuhfreader.adapter.ManualProductRecycleViewAdapter;
import com.eralink.unionuhfreader.adapter.ProductRecycleViewAdapter;
import com.eralink.unionuhfreader.adapter.RecycleViewDivider;
import com.eralink.unionuhfreader.base.BaseActivity;
import com.eralink.unionuhfreader.bean.AppMemberUserInfoRespVO;
import com.eralink.unionuhfreader.bean.CateProduct;
import com.eralink.unionuhfreader.bean.EPCBean;
import com.eralink.unionuhfreader.bean.FormOrder;
import com.eralink.unionuhfreader.bean.MessageEvent;
import com.eralink.unionuhfreader.bean.PayOrderPayTypeEnum;
import com.eralink.unionuhfreader.bean.Product;
import com.eralink.unionuhfreader.bean.ProductCategory;
import com.eralink.unionuhfreader.bean.ProductOrderDo;
import com.eralink.unionuhfreader.bean.ProductVo;
import com.eralink.unionuhfreader.bean.ReaderBean;
import com.eralink.unionuhfreader.bean.RetailProductPageReqVO;
import com.eralink.unionuhfreader.http.Api;
import com.eralink.unionuhfreader.http.JsonCallBack;
import com.eralink.unionuhfreader.http.Result;
import com.eralink.unionuhfreader.util.CacheNode;
import com.eralink.unionuhfreader.util.CachePool;
import com.eralink.unionuhfreader.util.Canstant;
import com.eralink.unionuhfreader.util.EPCReportDataParseUtil;
import com.eralink.unionuhfreader.util.EralinkApiErrDefinition;
import com.eralink.unionuhfreader.util.ErrString;
import com.eralink.unionuhfreader.util.SharedPreferencesUtil;
import com.eralink.unionuhfreader.util.StringUtils;
import com.eralink.unionuhfreader.util.ToastUtil;
import com.eralink.unionuhfreader.util.Utils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.Inflater;

import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

public class ManualCasherActivity extends BaseActivity implements EraLinkUHFReaderReportCallback {
    private TextView tx_member,tx_money_box,btn_order;

    /*商品列表*/
    private ManualProductRecycleViewAdapter manualProductRecycleViewAdapter;//所有商品适配器
    private LinearLayoutManager productLayloutManager;//布局管理器
    private RecyclerView productListView;
    private List<ProductVo> AllProducts = new ArrayList<>();
    /*购物车列表*/
    private ManualCateRecycleViewAdapter manualCateRecycleViewAdapter;
    private LinearLayoutManager productcateLayloutManager;//布局管理器
    private RecyclerView productcateListView;
    private List<CateProduct> cateProducts = new ArrayList<>();
    private EditText ed_searchstr;
    private Button btn_search,btn_refresh,btn_settle,btn_member;
    private TextView tx_cate_count, tx_cate_sale_count_price, tx_cate_dis_count_price, tx_pay_count,tv_exit;
    private HorizontalScrollView hsrollview;
    private LinearLayout ly_category;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manual);
        iniview();
        RetailProductPageReqVO vo= new RetailProductPageReqVO();
        getproductdata(vo);
        EventBus.getDefault().register(this);
        getcategory();
        connectReaderAction();
        timehandle.postDelayed(runnable, 1000 * 3);
        connectwoyou();//钱箱
     //   addEpc("31382DEA535C4D5C000");
    }

    private void getproductdata(RetailProductPageReqVO vo) {
        AllProducts.clear();
        BasePopupView popupView = new XPopup.Builder(this)
                .asLoading("正在同步数据....")
                .show();
        Api.getProduct(vo, new JsonCallBack<Result<String>>() {
            @Override
            public void onSuccess(Response<Result<String>> response) {
                popupView.dismiss();
                Result<String> result = response.body();
                System.out.println(result.getData());
                if (result.getData() != null) {
                    JSONObject jsonObject = JSON.parseObject(result.getData());
                    int total = jsonObject.getIntValue("total");
                    if (total > 0) {
                        List<ProductVo> productVos = JSON.parseArray(jsonObject.getString("list"), ProductVo.class);
                        AllProducts.addAll(productVos);
                        manualProductRecycleViewAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onError(Response<Result<String>> response) {
                super.onError(response);
                popupView.dismiss();
            }
        });
    }

    private void iniview() {
        tx_member = findViewById(R.id.tx_member);
        tx_member.setText("扫码获取会员");
        productListView = findViewById(R.id.rv_product);
        //
        tx_cate_count = findViewById(R.id.tx_cate_count);
        tx_cate_sale_count_price = findViewById(R.id.tx_cate_sale_count_price);
        tx_cate_dis_count_price = findViewById(R.id.tx_cate_dis_count_price);
        tx_pay_count = findViewById(R.id.tx_pay_count);
        ed_searchstr=findViewById(R.id.ed_searchstr);
        btn_search=findViewById(R.id.btn_search);
        btn_refresh=findViewById(R.id.btn_refresh);
        hsrollview=findViewById(R.id.hsrollview);
        ly_category=findViewById(R.id.ly_category);
        btn_member=findViewById(R.id.btn_member);
        tv_exit=findViewById(R.id.tv_exit);
        tx_money_box=findViewById(R.id.tx_money_box);
        btn_order=findViewById(R.id.btn_order);
        btn_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ManualCasherActivity.this,OrderActivity.class));
            }
        });
        tx_money_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openDrawer();
            }
        });
        tv_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ManualCasherActivity.this,LoginActivity.class));
                finish();
            }
        });
        btn_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showVipDialog();
            }
        });
        btn_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RetailProductPageReqVO vo=   new RetailProductPageReqVO();
                getproductdata(vo);
            }
        });
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RetailProductPageReqVO vo=   new RetailProductPageReqVO();
             if (ed_searchstr.getText()!=null&&!ed_searchstr.getText().toString().trim().equals("")){
                 vo.setBarCode(ed_searchstr.getText().toString().trim());
             }
             getproductdata(vo);
            }
        });
        productLayloutManager = new GridLayoutManager(this, 5);
        productListView.setLayoutManager(productLayloutManager);
        manualProductRecycleViewAdapter = new ManualProductRecycleViewAdapter(this, AllProducts);
        manualProductRecycleViewAdapter.setItemclick(new ManualProductRecycleViewAdapter.Itemclick() {
            @Override
            public void itemonclick(int postion) {
                ProductVo product = AllProducts.get(postion);
                addcate(product,1);
            }
        });
        productListView.setAdapter(manualProductRecycleViewAdapter);
        /*购物车*/
        productcateListView = findViewById(R.id.rv_cate);
        productcateListView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, R.drawable.item_divider));
        productcateLayloutManager = new LinearLayoutManager(this);
        productcateListView.setLayoutManager(productcateLayloutManager);
        manualCateRecycleViewAdapter = new ManualCateRecycleViewAdapter(this, cateProducts);
        manualCateRecycleViewAdapter.setCalCount(new ManualCateRecycleViewAdapter.CalCount() {
            @Override
            public void addOrDivClick(int postion, int count) {
                changeCate(postion,count);
            }
        });
        productcateListView.setAdapter(manualCateRecycleViewAdapter);
        btn_settle=findViewById(R.id.btn_settle);
        btn_settle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cateProducts.size()==0){
                    showToast("请选择商品后再结算");
                    return;
                }
                gotocreateOrder();
            }
        });
    }

    /**
     * 去创建订单
     */
    private void gotocreateOrder() {
        FormOrder formOrder=new FormOrder();
        if (MyApplication.memberUserInfoRespVO != null) {
            formOrder.setUserMobile(MyApplication.memberUserInfoRespVO.getMobile());
        }
        formOrder.setClientId(MyApplication.getSn());
        formOrder.setClientType("APP");
        formOrder.setStoreId(MyApplication.cashierDO.getStoreId());
        List<Product> products=new ArrayList<>();
        for (CateProduct productData : cateProducts) {
            Product product = new Product();
            product.setProductId(productData.getProductId());
            product.setCount(1);
            product.setDerate(0);
            product.setDiscount(0);
            products.add(product);
        }
        formOrder.setProducts(products);
        BasePopupView popupView = new XPopup.Builder(this)
                .asLoading("正在创建订单....")
                .show();

        Api.createOrder(formOrder, new JsonCallBack<Result<ProductOrderDo>>() {
            @Override
            public void onFinish() {
                super.onFinish();
                popupView.dismiss();
            }

            @Override
            public void onSuccess(Response<Result<ProductOrderDo>> response) {
                Result<ProductOrderDo> productOrderDoResult = response.body();
                if (productOrderDoResult != null && productOrderDoResult.isSucess()) {
                    Bundle bundle = new Bundle();
                    bundle.putString("products", JSON.toJSONString(cateProducts));
                    bundle.putSerializable("productorder", productOrderDoResult.getData());
                    Intent intent = new Intent(ManualCasherActivity.this, ManualSettlePlateformActivity.class);
                    intent.putExtra("p", bundle);
                    popupView.dismiss();
                    startActivity(intent);
                } else {
                    showToast(productOrderDoResult.getMsg());
                }
            }
        });
    }

    private void changeCate(int postion, int changecount) {
        if (changecount==0){
            cateProducts.remove(postion);
        }else {
            cateProducts.get(postion).setCount(cateProducts.get(postion).getCount()+changecount);
        }
        BigDecimal bigDecimal = BigDecimal.ZERO;
        int count = 0;
        for (CateProduct cateProduct : cateProducts) {
            bigDecimal = bigDecimal.add(new BigDecimal(cateProduct.getSalePrice()).multiply(new BigDecimal(cateProduct.getCount())));
            count = count + cateProduct.getCount();
        }

        //显示
        tx_cate_count.setText("共计:"+count+"件");
        tx_cate_sale_count_price.setText("原价:"+bigDecimal);
        tx_cate_dis_count_price.setText("优惠:0元");
        tx_pay_count.setText("合计:"+bigDecimal);
        manualCateRecycleViewAdapter.notifyDataSetChanged();
    }

    private void addcate(ProductVo product,int changecount) {

        boolean cantain = false;
        BigDecimal bigDecimal = BigDecimal.ZERO;
        int count = 0;
        for (CateProduct cateProduct : cateProducts) {
            if (cateProduct.getProductId().equals(product.getProductId())) {
                cantain = true;
                cateProduct.setCount(cateProduct.getCount() + changecount);
            }
            bigDecimal = bigDecimal.add(new BigDecimal(cateProduct.getSalePrice()).multiply(new BigDecimal(cateProduct.getCount())));
            count = count + cateProduct.getCount();

        }
        if (!cantain) {
            CateProduct cateProduct = new CateProduct();
            cateProduct.setProductName(product.getProductName());
            cateProduct.setProductId(product.getProductId());
            cateProduct.setCostPrice(product.getCostPrice());
            cateProduct.setSalePrice(product.getSalePrice());
            cateProduct.setEpc(product.getEpc());
            cateProduct.setBarCode(product.getBarCode());
            cateProduct.setViped(product.getViped());
            cateProduct.setCount(changecount);
            bigDecimal = bigDecimal.add(new BigDecimal(cateProduct.getSalePrice()).multiply(new BigDecimal(cateProduct.getCount())));
            count = count + cateProduct.getCount();
            cateProducts.add(cateProduct);
        }
        //显示
        tx_cate_count.setText("共计:"+count+"件");
        tx_cate_sale_count_price.setText("原价:"+bigDecimal);
        tx_cate_dis_count_price.setText("优惠:0元");
        tx_pay_count.setText("合计:"+bigDecimal);
        manualCateRecycleViewAdapter.notifyDataSetChanged();
    }
    @Subscribe
    public void onEvent(MessageEvent messageEvent){
        switch (messageEvent.getType()){
            case 0:
                //取消订单
                resetData();
                break;
            case 1:
                //重新计算
                break;
            case 2:
                //支付成功
                resetData();
                String paytype=messageEvent.getData().toString();
                if (paytype.equals(PayOrderPayTypeEnum.CashPayment.getCode())){
                    openDrawer();
                }
                break;
        }
    }
   private  void   resetData(){
       cateProducts.clear();
       manualCateRecycleViewAdapter.notifyDataSetChanged();
       tx_cate_count.setText("共计:");
       tx_cate_sale_count_price.setText("原价:");
       tx_cate_dis_count_price.setText("优惠:");
       tx_pay_count.setText("共计:");
    }
    @Override
    protected void onDestroy() {
        if (uhfReaderInterface != null) {
            uhfReaderInterface.close();
            uhfReaderInterface = null;
        }
        super.onDestroy();
        unbindService(connection2);
        EventBus.getDefault().unregister(this);
    }

    public void getcategory(){
        Api.getcategory(new JsonCallBack<Result<List<ProductCategory>>>(){
            @Override
            public void onSuccess(Response<Result<List<ProductCategory>>> response) {
                Result<List<ProductCategory>> body=response.body();
                if (body!=null&&body.isSucess()){
                    for (ProductCategory datum : body.getData()) {
                        View v= getLayoutInflater().inflate(R.layout.item_category,null);
                        TextView textView=v.findViewById(R.id.category_item_name);
                        textView.setText(datum.getName());
                        v.setTag(datum);
                        v.setOnClickListener(itemcategoryClick);
                        ly_category.addView(v);
                    }
                }
            }
        });
    }

    public View.OnClickListener itemcategoryClick=new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ProductCategory data= (ProductCategory) view.getTag();
            RetailProductPageReqVO vo=new RetailProductPageReqVO();
            vo.setCategoryId(data.getId());
            getproductdata(vo);
            Log.i("ykj",JSON.toJSONString(data));
        }
    };

    /********************监听扫码***********************/
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        switch (action) {
            case KeyEvent.ACTION_DOWN:
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
                    return super.dispatchKeyEvent(event);
                }
                if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                    return super.dispatchKeyEvent(event);
                }
                int unicodeChar = event.getUnicodeChar();
                sb.append((char) unicodeChar);
                Log.e("MainActivity", "dispatchKeyEvent: " + unicodeChar + " " + event.getKeyCode() + " scancode=" + event.getScanCode());
                len++;
                startScan();
                return true;
            default:
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    private Handler myHandler = new Handler();
    int oldLen = 0;
    boolean isScaning = false;
    private StringBuilder sb = new StringBuilder();
    int len = 0;
    private void startScan() {
        if (isScaning) {
            return;
        }
        isScaning = true;
        timerScanCal();
    }

    private void timerScanCal() {
        oldLen = len;
        myHandler.postDelayed(scan, 100);
    }

    Runnable scan = new Runnable() {
        @Override
        public void run() {
            if (oldLen != len) {
                timerScanCal();
                return;
            }
            isScaning = false;
            if (sb.length() > 0) {
                excCode(sb.toString());
                sb.setLength(0);
            }
        }
    };
    private void excCode(String code){
        //showToast(code);
        code = code.replaceAll("[^0-9a-zA-Z]", "");
        Log.e(ManualCasherActivity.class.getSimpleName(), "扫码===" + code);
        getproductAndAddCate(code);
    }

    private void getproductAndAddCate(String code) {
        RetailProductPageReqVO vo=new RetailProductPageReqVO();
        vo.setBarCode(code);
        BasePopupView popupView = new XPopup.Builder(this)
                .asLoading("正在查询商品....")
                .show();
        Api.getProduct(vo, new JsonCallBack<Result<String>>() {
            @Override
            public void onSuccess(Response<Result<String>> response) {
                popupView.dismiss();
                Result<String> result = response.body();
                System.out.println(result.getData());
                if (result.getData() != null) {
                    JSONObject jsonObject = JSON.parseObject(result.getData());
                    int total = jsonObject.getIntValue("total");
                    if (total > 0) {
                        if (total==1){
                            List<ProductVo> productVos = JSON.parseArray(jsonObject.getString("list"), ProductVo.class);
                            addcate(productVos.get(0),1);
                        }else{
                            AllProducts.clear();
                            List<ProductVo> productVos = JSON.parseArray(jsonObject.getString("list"), ProductVo.class);
                            AllProducts.addAll(productVos);
                            manualProductRecycleViewAdapter.notifyDataSetChanged();
                        }
                    }else {
                        showToast("该门店没有对应的商品");
                    }
                }
            }

            @Override
            public void onError(Response<Result<String>> response) {
                super.onError(response);
                popupView.dismiss();
            }
        });
    }
    /***********************监听结束*********************/
    /*获取会员*/
    public void  showVipDialog(){
        BasePopupView v=  new XPopup.Builder(this).asInputConfirm("输入会员手机号", "",
                        new OnInputConfirmListener() {
                            @Override
                            public void onConfirm(String text) {
                                getmember(text);
                            }
                        })
                .show();
    }
    private void getmember(String mobile) {
        Api.getmemberinfo(mobile,new JsonCallBack<Result<AppMemberUserInfoRespVO>>(){
            @Override
            public void onSuccess(Response<Result<AppMemberUserInfoRespVO>> response) {
                Result<AppMemberUserInfoRespVO> appMemberUserInfoRespVOResult=response.body();
                if (appMemberUserInfoRespVOResult.isSucess()){
                    MyApplication.memberUserInfoRespVO=appMemberUserInfoRespVOResult.getData();
                    tx_member.setText(MyApplication.memberUserInfoRespVO.getMobile());
                }else {
                    showToast(appMemberUserInfoRespVOResult.getMsg());
                }
            }
        });
    }
    /************************   private EraLinkUHFReaderInterface uhfReaderInterface RFID 读卡器*****************************/
    private byte reader_id = 0;
    private final AtomicInteger tagReportTotalNumber = new AtomicInteger(0);
    private final AtomicInteger statisticsIntervalTagNumber = new AtomicInteger(0);
    private static final int cmd_update_epc = 0x01;
    private static final int cmd_update_inventory_statistic = 0x02;
    private static final int cmd_report_io_failed = 0x03;
    private static final int cmd_auto_read_update = 0x04;
    private static final int cmd_update_auto_read_statistic = 0x05;
    private static final int cmd_multi_bank_auto_read_update = 0x06;
    private static final int cmd_reader_connect = 0x07;
    private static final int cmd_reader_disconnect = 0x08;
    private static final int cmd_others_report = 0xFF;
    private final Handler epcReportHandler = new EPCReportHandler(this);
    private int reader_work_role = -1; // 0, server; 1, client
    private final Hashtable<String, EPCBean> epcBeanMap = new Hashtable<>();
    private EraLinkUHFReaderInterface uhfReaderInterface;
    Handler timehandle = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            inventoryOnceAction();
            timehandle.postDelayed(runnable, 1000 * 3);
        }
    };
    private boolean checkOpenRfid(){
        int i= (int) SharedPreferencesUtil.getData(this, Canstant.RFID_SWITCH_KEY,0);
        if (i==0){
            return false;
        }
        return true;
    }
    private void inventoryOnceAction() {
        if (!checkOpenRfid()){
            return;
        }
        if (uhfReaderInterface != null) {
            final int result = uhfReaderInterface.inventoryOnce(reader_id);
            //Toast.makeText(this, getResources().getString(ErrString.getErrId(result)), Toast.LENGTH_SHORT).show();
        } else {
             Log.i(ManualCasherActivity.class.getSimpleName(), "读卡器未连接");
             Toast.makeText(this, getResources().getString(R.string.connect_reader), Toast.LENGTH_SHORT).show();
        }
    }
    private void connectReaderAction() {
        if (!checkOpenRfid()){
            return;
        }
        if (uhfReaderInterface != null) {
            return;
        }
        String connectStr = String.format(Locale.getDefault(), "CommType=COM;ComPath=%s;Address=1;Baud=%d;Databits=8;Stopbits=1;Parity=0", "/dev/ttyS4", 115200);
        uhfReaderInterface = new EraLinkUHFReaderInterface();
        final int result = uhfReaderInterface.connect(connectStr, this);
        if (EralinkApiErrDefinition.ErrNoError != result) {
            uhfReaderInterface = null;
            Toast.makeText(this, getResources().getString(ErrString.getErrId(result)), Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(this, "设备链接成功", Toast.LENGTH_SHORT).show();
        //setControlStatusOnReaderConnectStatus(true);
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void report(byte reader_id, int report_cmd_code, byte[] report_data, int report_data_len) {
        String message = String.format("[%s] reader_id: %s, report_cmd_code: %s, report_data: %s, report_data_len: %s.\n",
                Utils.getCurrentTime(), reader_id, report_cmd_code, StringUtils.bytesToHexString(report_data, 0, report_data_len), report_data_len);
        Log.d("ykj520", message);

        if (report_cmd_code == EraLinkUHFReaderCmdCode.CmdInventoryOnce || report_cmd_code == EraLinkUHFReaderCmdCode.CmdStartInventory) {
            //对盘点一次，report_cmd_code=37；对连续盘点，report_cmd_code=42
            reportForInventory(reader_id, report_data, report_data_len);
        } else if (report_cmd_code == EraLinkUHFReaderCmdCode.CmdStartMultiBankAutoRead) {
            //2.2.11.	多区域自动读卡上报
            reportForMultiBankAutoRead(reader_id, report_data, report_data_len);
        } else if (report_cmd_code == EraLinkUHFReaderCmdCode.CmdStartAutoRead) {
            //2.2.8.	自动读卡上报
            reportForAutoRead(reader_id, report_data, report_data_len);
        } else if (report_cmd_code == EraLinkUHFReaderCmdCode.CmdDeviceInfoReport) {
            //2.2.5.	读写器连接上报 在读写器作为Tcp Client时，会上报设备IP、序列号信息和设备名称，这时，report_cmd_code=103，
            reportReaderConnect(reader_id, report_data, report_data_len);
        } else if (report_cmd_code == EraLinkUHFReaderCmdCode.CmdReaderCommunicationBreak) {
            //如果读写器断开，则report_cmd_code=255，report_data_len=0
            reportReaderDisconnect(reader_id);
        } else {
            reportForOthers(reader_id, message);
        }
    }
    private void reportForInventory(byte reader_id, final byte[] report_data, int report_data_len) {
        if (9 > report_data_len) {
            return;
        }

        tagReportTotalNumber.incrementAndGet();
        statisticsIntervalTagNumber.incrementAndGet();

        CacheNode cacheNode = CachePool.getInstance().obtain(1 + report_data_len);
        cacheNode.getBuffer()[0] = reader_id;
        System.arraycopy(report_data, 0, cacheNode.getBuffer(), 1, report_data_len);
        cacheNode.setBufferSize(1 + report_data_len);

        Message message = new Message();
        message.what = cmd_update_epc;
        message.obj = cacheNode;
        epcReportHandler.sendMessage(message);
    }
    private void reportForAutoRead(byte reader_id, final byte[] report_data, int report_data_len) {
        if (1 >= report_data_len) {
            return;
        }
        CacheNode cacheNode = CachePool.getInstance().obtain(1 + report_data_len);
        cacheNode.getBuffer()[0] = reader_id;
        System.arraycopy(report_data, 0, cacheNode.getBuffer(), 1, report_data_len);
        cacheNode.setBufferSize(1 + report_data_len);

        Message message = new Message();
        message.what = cmd_auto_read_update;
        message.obj = cacheNode;
        epcReportHandler.sendMessage(message);
    }

    private void reportForMultiBankAutoRead(byte reader_id, final byte[] report_data, int report_data_len) {
        if (1 >= report_data_len) {
            return;
        }

        CacheNode cacheNode = CachePool.getInstance().obtain(1 + report_data_len);
        cacheNode.getBuffer()[0] = reader_id;
        System.arraycopy(report_data, 0, cacheNode.getBuffer(), 1, report_data_len);
        cacheNode.setBufferSize(1 + report_data_len);

        Message message = new Message();
        message.what = cmd_multi_bank_auto_read_update;
        message.obj = cacheNode;
        epcReportHandler.sendMessage(message);
    }

    private void reportReaderConnect(byte reader_id, final byte[] report_data, int report_data_len) {
        if (reader_work_role == 0) {
            return;
        }
        final String device_info = new String(report_data, 0, report_data_len);
        final String[] fields = device_info.split(",");
        ReaderBean readerBean = new ReaderBean();
        readerBean.setReaderId(reader_id);
        if (fields.length == 2) {
            readerBean.setSn(fields[0]);
            readerBean.setName(fields[1]);
        } else { // fields.length == 3
            readerBean.setIp(fields[0]);
            readerBean.setSn(fields[1]);
            readerBean.setName(fields[2]);
        }

        Message message = new Message();
        message.what = cmd_reader_connect;
        message.obj = readerBean;
        epcReportHandler.sendMessage(message);
    }

    private void reportReaderDisconnect(byte reader_id) {
        Message message = new Message();
        message.what = cmd_reader_disconnect;
        message.obj = reader_id;
        epcReportHandler.sendMessage(message);
    }

    private void reportForOthers(byte reader_id, String report) {
        Message message = new Message();
        message.what = cmd_others_report;
        message.obj = report;
        epcReportHandler.sendMessage(message);
    }

    private static class EPCReportHandler extends Handler {
        private final WeakReference<ManualCasherActivity> mainActivityWeakReference;

        public EPCReportHandler(ManualCasherActivity mainActivity) {
            mainActivityWeakReference = new WeakReference<>(mainActivity);
        }

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case cmd_report_io_failed:
                    //processIOFailed((Integer) msg.obj);
                    break;
                case cmd_update_epc:
                    updateInventory(msg);
                    break;
                case cmd_update_inventory_statistic:
                    //updateStatistics();
                    break;
                case cmd_multi_bank_auto_read_update:
                    //updateMultiBankAutoRead(msg);
                    break;
                case cmd_auto_read_update:
                    //updateAutoRead(msg);
                    break;
                case cmd_update_auto_read_statistic:
                    //updateAutoReadStatistics();
                    break;
                case cmd_reader_connect:
                    processReaderConnect(msg);
                    break;
                case cmd_reader_disconnect:
                    //processReaderDisconnect(msg);
                    break;
                case cmd_others_report:
                    //othersReport(msg);
                default:
                    break;
            }
        }

        private void updateInventory(Message msg) {
            ManualCasherActivity mainActivity = mainActivityWeakReference.get();
            if (mainActivity == null) {
                return;
            }
            CacheNode cacheNode = (CacheNode) msg.obj;
            final EPCBean epcBean = new EPCBean();
            EPCReportDataParseUtil.parseInventoryEPCReport(cacheNode, epcBean);
            CachePool.getInstance().release(cacheNode);

            EPCBean oldEpcBean = mainActivity.epcBeanMap.get(epcBean.getKey());
            if (oldEpcBean != null) {
                oldEpcBean.setRssi(epcBean.getRssi());
                oldEpcBean.setAnt(epcBean.getAnt());
                oldEpcBean.setCount(oldEpcBean.getCount() + 1);
            } else {
                epcBean.setCount(1);
                mainActivity.addEpc(epcBean.getEPC());
                mainActivity.epcBeanMap.put(epcBean.getKey(), epcBean);
            }
        }

        private void processReaderConnect(Message msg) {
            ManualCasherActivity readActivity = mainActivityWeakReference.get();
            if (readActivity == null) {
                return;
            }
            ReaderBean readerBean = (ReaderBean) msg.obj;
            readActivity.reader_id = readerBean.getReaderId();
        }
    }
    private void addEpc(String epc) {
        Log.d("读到EPC", epc);
        RetailProductPageReqVO vo=new RetailProductPageReqVO();
        vo.setEpc(epc);
        Toast.makeText(this,epc,Toast.LENGTH_LONG).show();
        Api.getproductByEpc(epc, new JsonCallBack<Result<String>>() {
            @Override
            public void onSuccess(Response<Result<String>> response) {
                Result<String> result = response.body();
                System.out.println(result.getData());
                if (result.getData() != null) {
                    JSONObject jsonObject = JSON.parseObject(result.getData());
                    ProductVo productVos = JSON.parseObject(jsonObject.toJSONString(), ProductVo.class);
                    addcate(productVos,1);
                }
            }
        });
    }
    /*钱箱*/
    private IWoyouService manager;
    //钱箱服务
    private void connectwoyou() {
        Intent intent = new Intent();
        intent.setPackage("woyou.aidlservice.jiuiv5");
        intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
        bindService(intent, connection2, Context.BIND_AUTO_CREATE);
    }

    //钱箱服务
    ServiceConnection connection2 = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(ManualCasherActivity.class.getSimpleName(), "onServiceConnected");
            manager = IWoyouService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            manager = null;
        }
    };
    /**
     * 打开钱箱
     */
    private void openDrawer() {
        try {
            if (manager == null) {
                ToastUtil.showToast("钱箱未连接");
                return;
            }
            manager.openDrawer(new ICallback() {
                @Override
                public void onRunResult(boolean isSuccess, int code, String msg) throws RemoteException {
                    if (isSuccess) {
                        Log.d(ManualCasherActivity.class.getSimpleName(), "打开钱箱成功");
                    }
                }

                @Override
                public IBinder asBinder() {
                    return null;
                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
